﻿Imports LRS.BLL
Imports LRS.DTO
Imports System.Collections.Generic
Imports System.Windows.Forms
Public Class CreateOrder
    Private Class ProductOrder

        Private _ProductID As Integer
        Public Property ProductID() As Integer
            Get
                Return _ProductID
            End Get
            Set(ByVal value As Integer)
                _ProductID = value
            End Set
        End Property

        Private _ProductName As String
        Public Property ProductName() As String
            Get
                Return _ProductName
            End Get
            Set(ByVal value As String)
                _ProductName = value
            End Set
        End Property


        Private _RentingPrice As Single
        Public Property RentingPrice() As Single
            Get
                Return _RentingPrice
            End Get
            Set(ByVal value As Single)
                _RentingPrice = value
            End Set
        End Property

        Private _MaxQuantity As String
        Public Property MaxQuantity() As String
            Get
                Return _MaxQuantity
            End Get
            Set(ByVal value As String)
                _MaxQuantity = value
            End Set
        End Property

        Private _Quantity As Integer
        Public Property Quantity() As Integer
            Get
                Return _Quantity
            End Get
            Set(ByVal value As Integer)
                _Quantity = value
            End Set
        End Property


        Private _Price As Single
        Public ReadOnly Property Price() As Single
            Get
                Return _RentingPrice * _Quantity
            End Get
        End Property
    End Class
    Private products As List(Of ProductOrder)
    Private Sub CreateOrder_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        products = New List(Of ProductOrder)
        lblEmployeeNumber.Text = LRSInfo.Username
        lblDateOfBill.Text = DateTime.Now.ToString("dd/MM/yyyy")
        lblDateOfReturn.Text = DateTime.Now.AddDays(2).ToString("dd/MM/yyyy")
        lblTotalAmount.Text = "0"
        DateTimePicker.MinDate = DateTime.Now
        DateTimePicker.MaxDate = DateTime.Now.AddDays(LRSInfo.MaxDay)
        gridOrder.AutoGenerateColumns = False
    End Sub

    Public Function AddProduct(ByVal product As eProduct) As Boolean
        Dim sumQty As Integer = 0
        Dim i As Integer
        Dim flag As Boolean = False
        For i = 0 To products.Count - 1
            sumQty = sumQty + products(i).Quantity
            If (sumQty >= LRSInfo.MaxQuantity) Then
                MessageBox.Show("Số lượng hàng vượt quá giới hạn cho phép. Tối đa một lần mượn được " & LRSInfo.MaxQuantity)
                Return False
            End If
            If (products(i).ProductID = product.ProductID) Then
                MessageBox.Show("Sản phẩm này đã có trong đơn hàng")
                Return False
            End If
        Next
        If (flag = False) Then
            Dim po As ProductOrder = New ProductOrder()
            po.ProductName = product.ProductName
            po.Quantity = 1
            po.RentingPrice = product.RentingPrice
            po.ProductID = product.ProductID
            po.MaxQuantity = product.Quantity
            products.Add(po)
        End If
        gridOrder.DataSource = Nothing
        gridOrder.DataSource = products
        UpdateTotal()
        Return True
    End Function

    Private Sub btnAddProduct_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddProduct.Click
        Dim sp As SelectProduct = New SelectProduct()
        sp.Owner = Me
        sp.ShowDialog()
    End Sub

    Private Sub DateTimePicker_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker.ValueChanged
        lblDateOfReturn.Text = DateTimePicker.Value.ToString("dd/MM/yyyy")
        UpdateTotal()
    End Sub

    Private Sub gridOrder_Validated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gridOrder.Validated
        UpdateTotal()
    End Sub

    Private Sub gridOrder_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridOrder.CellEndEdit
        gridOrder.Refresh()
        UpdateTotal()
    End Sub
    Private Sub UpdateTotal()
        Dim sum As Single = 0
        For i = 0 To products.Count - 1
            sum += products(i).Price
        Next
        sum = sum * (DateTime.Parse(lblDateOfReturn.Text).Subtract(DateTime.Now).Days + 1)
        lblTotalAmount.Text = sum.ToString("#,#")
    End Sub


    Private Sub gridOrder_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles gridOrder.DataError
        MessageBox.Show("Thông tin nhập không hợp lệ")
        e.Cancel = True
    End Sub

    Private Sub btnRemoveProduct_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemoveProduct.Click
        If (gridOrder.SelectedCells.Count = 0) Then
            MessageBox.Show("Chọn một dòng để xóa")
            Return
        End If
        Dim row As Integer = gridOrder.SelectedCells(0).RowIndex
        gridOrder.DataSource = Nothing
        products.RemoveAt(row)
        gridOrder.DataSource = products
        UpdateTotal()
    End Sub

    Private Sub gridOrder_CellValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles gridOrder.CellValidating
        Dim headerText As String = gridOrder.Columns(e.ColumnIndex).Name
        If (Not headerText.Equals("Quantity")) Then
            Return
        End If
        Dim quantity As Integer
        quantity = Int32.Parse(e.FormattedValue.ToString())
        If (quantity > products(e.RowIndex).MaxQuantity) Then
            MessageBox.Show("Số lượng yêu cầu vượt quá số lượng còn trong kho")
            e.Cancel = True
        Else
            Dim productID As Integer = gridOrder.Rows(e.RowIndex).Cells("ProductID").Value
            Dim sum As Integer = 0
            For Each prod As ProductOrder In products
                sum = sum + prod.Quantity
                If (productID = prod.ProductID) Then
                    sum = sum - prod.Quantity + e.FormattedValue
                End If
            Next
            If (sum > LRSInfo.MaxQuantity) Then
                MessageBox.Show("Số lượng hàng vượt quá giới hạn cho phép. Tối đa một lần mượn được " & LRSInfo.MaxQuantity)
                Return
            End If
        End If
    End Sub

    Private Sub btnFinish_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFinish.Click
        If (txtCustomerNumber.Text.Trim().Length() = 0) Then
            MessageBox.Show("Vui lòng nhập mã khách hàng")
            Return
        End If
        If (gridOrder.Rows.Count = 0) Then
            Dim result = MessageBox.Show("Bạn chưa chọn sản phẩm nào cả. Hủy đơn hàng?", "Xác nhận", MessageBoxButtons.YesNo)
            If (result = DialogResult.Yes) Then
                Me.Close()
            ElseIf (result = DialogResult.No) Then
                Return
            End If
        End If
        Dim order As eSalesOrder = New eSalesOrder()
        order.EmployeeID = Int32.Parse(lblEmployeeNumber.Text.Substring(3))
        order.CustomerID = Int32.Parse(txtCustomerNumber.Text.Substring(1))
        order.DateOfBill = DateTime.Now.ToString("dd/MM/yyyy")
        order.DateOfReturn = DateTime.Parse(lblDateOfReturn.Text)
        order.TotalAmount = Single.Parse(lblTotalAmount.Text)
        order.OnHold = True
        bSalesOrder.InsertOrder(order)
        Dim detail As eSalesOrderDetail = New eSalesOrderDetail()
        detail.SalesOrderID = order.SalesOrderID
        Dim index As Integer
        For index = 0 To products.Count - 1
            detail.ProductID = products(index).ProductID
            detail.Quantity = products(index).Quantity
            detail.TotalAmount = products(index).Price
            detail.Description = ""
            detail.AddedFee = 0
            bSalesOrderDetail.Insert(detail)
        Next
        MessageBox.Show("Giao dịch thành công")
        Me.Close()
    End Sub

    Private Sub btnMore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMore.Click
        Dim manageCustomer As ManageCustomer = New ManageCustomer()
        manageCustomer.SelectCustomer()
        manageCustomer.ShowDialog()
        txtCustomerNumber.Text = manageCustomer.SelectedCustomerNumber
    End Sub

    
    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub
End Class